/*
 * @Author: Administrator
 * @Date:   2020-07-15 16:11:14
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-26 17:13:14
 */

'use strict'
const path = global.path = require('path');
const fs = global.fs = require('fs');

/*主进程入口文件*/
const app = global.app = require('electron').app;
const remote = global.remote = require('electron').remote;
const BrowserWindow = global.BrowserWindow = require('electron').BrowserWindow;
const ipcMain = global.ipcMain = require('electron').ipcMain;
const dialog = global.dialog = require('electron').dialog;

/*相关配置文件*/
const {
  mainConfig,
  subConfig
} = require('./lib/main.config.js')

/*初始化主窗口，不然会被垃圾机制回收*/
let mainWindow

//主程序窗口
function createMainWindow() {
  mainWindow = new BrowserWindow(mainConfig);

  // mainWindow = new BrowserWindow(mainConfig);
  mainWindow.loadFile(mainConfig.template);

  // 打开chrome开发者工具
  mainWindow.webContents.openDevTools();

  // !无效的事件 窗口初始化后要执行的函数
  mainWindow.on('ready-to-show', (e) => {
    console.log('ready-to-show')
  })

  // 关闭
  mainWindow.on('closed', function() {
    mainWindow = null
    subWindow = null
  })
}


//关闭chrome的缓存
app.commandLine.appendSwitch("--disable-http-cache")
//关闭GPU硬件加速
app.disableHardwareAcceleration()

//创建主进程窗口
app.on('ready', () => {
  createMainWindow();
})


//创建结束事件
app.on('window-all-closed', function() {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

//如果
app.on('activate', function() {
  console.log(`出发activate事件`)
  if (mainWindow === null) createWindow()
})



//******************************************************
//子窗口相关事件
//
//创建子窗口
const createSubWindow = require('./lib/subWindows.js')
let subWindow = global.subWindow = null

// 接收事件,创建子窗口
ipcMain.on('create-subWindow', (e, options) => {
  //如果子窗口未创建,则进行创建
  console.log('create-subWindow')
  if (options) Object.assign(subConfig, options)
  subWindow = createSubWindow(subConfig)
})

// 设置channel
ipcMain.on('subWindow-ready', (e) => {
  console.log('subWindow-ready sucessfully: ')
  //当渲染进程的实例被成功创建，此时返回进程通讯的对象
  subWindow.channel = e
})

// 发送消息
ipcMain.on('new-msg', (e, msg) => {
  console.log('new-msg sucessfully: ' + msg)
  //当渲染进程的实例被成功创建，此时返回进程通讯的对象
  if (subWindow.channel) {
    subWindow.send('push-msg', msg)
  }
})

// 隐藏和显示监听
ipcMain.on('show-subWindow', (e, stat) => {
  if (stat) {
    subWindow.win.hiden()
    e.reply('subWindow-hiden')
  } else {
    subWindow.win.show()
    e.reply('subWindow-show')
  }
})

//关闭子窗口
ipcMain.on('close-subWindow', (e, stat) => {
  subWindow.win = null
  subWindow = null
})

// require('./lib/main.event.js');